package com.Servlet;

import com.DAO.GradeDao;
import com.Grade;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/addGrade")
public class AddGradeServlet extends HttpServlet {
    private GradeDao gradeDao;

    @Override
    public void init() throws ServletException {
        gradeDao = new GradeDao();  // 初始化GradeDao对象
    }

    // 处理GET请求，显示新增成绩页面
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 转发到新增成绩的页面
        request.getRequestDispatcher("addGrade.jsp").forward(request, response);
    }

    // 处理POST请求，接收表单数据并添加成绩
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        try {
            // 获取表单数据
            int studentId = Integer.parseInt(request.getParameter("studentId"));
            String courseName = request.getParameter("courseName");
            double gradeValue = Double.parseDouble(request.getParameter("grade"));

            // 创建Grade对象
            Grade grade = new Grade();
            grade.setStudentId(studentId);
            grade.setCourseName(courseName);
            grade.setGrade(String.valueOf(gradeValue));  // 转为字符串存储

            // 插入成绩数据到数据库
            gradeDao.addGrade(grade);

            // 成功后重定向到成绩管理页面
            response.sendRedirect("gradeManagement");

        } catch (NumberFormatException | SQLException e) {
            e.printStackTrace();
            // 如果有错误，返回新增成绩页面并显示错误信息
            request.setAttribute("errorMessage", "添加成绩失败，请检查输入！");
            request.getRequestDispatcher("addGrade.jsp").forward(request, response);
        }
    }
}
